<?php

namespace app\common\helper;

class SSEHelper
{
    /**
     * newLineChar
     * @var string
     */
    private static string $newLineChar = "\n\n";

    /**
     * splitLineChar
     * @var string
     */
    private static string $splitLineChar = "\n";

    /**
     * setHttpHeader
     * @return void
     */
    public static function setHttpHeader()
    {
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        header('X-Accel-Buffering: no');
    }

    /**
     * splitMessageByLineChar
     * @param $message
     * @return false|string[]
     */
    public static function splitMessageByLineChar($message)
    {
        return explode(self::$splitLineChar, $message);
    }

    /**
     * 格式化每行信息
     * @param $message
     * @return array
     */
    public static function formatMessage($message): array
    {
        $messageNodes = explode(':', $message);
        if (!$messageNodes) {
            return [];
        }
        $messageKey = $messageNodes[0];
        $messageVal = str_replace($messageKey . ':', '', $message);
        return [
            'key' => trim($messageKey),
            'val' => trim($messageVal),
        ];
    }

    /**
     * buildMessage
     * @param $key
     * @param $val
     * @return string
     */
    public static function buildMessage($key, $val): string
    {
        return $key . ':' . json_encode($val, 256);
    }

    /**
     * flushMessage
     * @param $key
     * @param $val
     * @return void
     */
    public static function flushMessage($key, $val)
    {
        $message = self::buildMessage($key, $val);
        echo $message . self::$newLineChar;
        ob_flush();
        flush();
    }

    /**
     * createMessage
     * @return array
     */
    public static function createMessage(): array
    {
        return ['code' => 1, 'data' => '', 'finish' => false,];
    }

    /**
     * flushSuccessMessage
     * @param $data
     * @param bool $finish
     * @param string $key
     */
    public static function flushSuccessMessage($data, bool $finish = false, string $key = 'data')
    {
        self::flushMessage($key, ['code' => 1, 'data' => $data, 'finish' => $finish]);
    }

    /**
     * flushFailMessage
     * @param $data
     * @param string $key
     */
    public static function flushFailMessage($data, string $key = 'data')
    {
        self::flushMessage($key, ['code' => 0, 'data' => $data, 'finish' => true]);
    }
}